package com.imooc.infra.repository;

import com.imooc.business.domain.Metadata;
import com.imooc.business.domain.Organ;
import com.imooc.infra.mapping.MetadataMapping;
import com.imooc.infra.mapping.OrganMapping;
import com.imooc.infra.repository.entity.TDataCenterMetadata;
import com.imooc.infra.repository.entity.TDataCenterOrgan;
import com.imooc.infra.repository.service.ITDataCenterMetadataService;
import com.imooc.infra.repository.service.ITDataCenterOrganService;
import lombok.Setter;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Repository
public class OrganRepository {

    @Setter(onMethod_ = @Autowired)
    private ITDataCenterOrganService organService;
    @Setter(onMethod_ = @Autowired)
    private OrganMapping organMapping;

    public List<Organ> listByRuleId(Long ruleId) {
        List<TDataCenterOrgan> organs = organService.listByRuleId(ruleId);
        return organs.stream().map(organMapping::toVo).collect(Collectors.toList());
    }

    public List<Organ> saveOrgan(Long ruleId, List<Organ> organs) {
        List<TDataCenterOrgan> entityList = organs.parallelStream().map(organMapping::toEntity).
                peek(entity -> entity.setRuleId(ruleId)).
                collect(Collectors.toList());
        boolean saveBatch = organService.saveBatch(entityList);
        if (saveBatch) {
            return entityList.stream().map(organMapping::toVo).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }
}
